package week10;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

/**
 * @author The setting sun
 * @version 1.0
 * @title: Work5
 * @description: TODO
 * @date 2021/11/11 15:16
 */
public class Work5 {
    public static void main(String[] args) {
        try {
            new MyFrame2().Init();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class MyFrame2 {
    JFrame frame = new JFrame();
    JLabel title = new JLabel("抽奖");
    JLabel label = new JLabel("中奖人：");
    JButton b1 = new JButton("开始");
    JButton b2 = new JButton("停止");
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel();
    Boolean isStop = false;
    FileReader fr;
    BufferedReader br;
    File file;

    public void Init() throws FileNotFoundException {
        file = new File("src\\抽奖名单.txt");
        fr = new FileReader(file);
        br = new BufferedReader(fr);

        try {
            br.mark((int) (file.length()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        frame.setLayout(new GridLayout(3, 1));
        title.setFont(new Font("微软雅黑", Font.BOLD, 28));
        label.setFont(new Font("微软雅黑", Font.BOLD, 18));


        p1.add(title);
        p2.add(label);
        p3.add(b1);
        p3.add(b2);

        frame.add(p1);
        frame.add(p2);
        frame.add(p3);

        frame.setVisible(true);
        frame.setSize(550, 400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        b1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                isStop = true;
            }
        });

        b2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                isStop = false;
            }
        });

        class MyThread extends Thread {
            @Override
            public void run() {
                while (true) {
                    if (isStop) {
                        try {
                            sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        try {
                            String str = br.readLine();
                            if (str != null) {
                                label.setText("中奖人：" + str);
                            } else {
                                br.reset();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        new MyThread().start();
    }

}


